﻿using System.Linq;
using NetSurveillance.WebApp.DataServices.Models;
using ServiceStack.OrmLite;

namespace NetSurveillance.WebApp.DataServices.Implementations
{
    public class IpSettingService : BaseService<IpSetting>
    {
        public IpSettingService(string connStr, IOrmLiteDialectProvider provider = null)
            : base(connStr, provider)
        {
        }

        /// <summary>
        /// 获取数据表中最新的一条IPSetting记录，如果表为空，则新建一条
        /// </summary>
        /// <param name="deviceName">设备名：如eth0</param>
        /// <returns>数据表中最新的一条IPSetting记录</returns>
        public IpSetting GetLastIpSetting(string deviceName)
        {
            IpSetting ipSetting;
            using (var db = DbFactory.OpenDbConnection())
            {
                const string sqlStr =
                    @"insert into ""IpSettings""(""DeviceName"",""Ip"",""SubnetMask"",""Gateway"",""StatusToken"") 
                        select :deviceName,'','','',1 
                            where not exists(select 1 from ""IpSettings"" where ""StatusToken""!=0 and ""DeviceName""=:deviceName); 
                      select * from ""IpSettings"" 
                        where ""StatusToken""!=0 and ""DeviceName""=:deviceName order by ""Id"" desc limit 1";
                ipSetting =
                    db.SqlList<IpSetting>(sqlStr, new {deviceName}).FirstOrDefault();
            }
            return ipSetting;
        }
    }
}